<template>
    <div class="page-sell">
        <van-nav-bar
            title="Feedback"
            left-arrow
            @click-left="onClickLeft"
        />

        <van-panel title="Type" desc="" status="">
            <van-radio-group v-model="form.radio">
                <van-cell-group>
                    <van-cell title="Software error" clickable @click="form.radio = '1'">
                        <van-radio name="1"/>
                    </van-cell>
                    <van-cell title="Feature request" clickable @click="form.radio = '3'">
                        <van-radio name="3"/>
                    </van-cell>
                    <van-cell title="Others" clickable @click="form.radio = '5'">
                        <van-radio name="5"/>
                    </van-cell>
                </van-cell-group>
            </van-radio-group>
            <van-cell-group>
                <van-field
                    v-model="form.feedbackValue"
                    label="Feedback"
                    type="textarea"
                    placeholder="Write feedback"
                    rows="4"
                    :autosize="{minHeight: 80}"
                />
            </van-cell-group>
        </van-panel>


        <van-panel title="Screen Shots (Max. 6)" desc="" status="">
            <div class="upload-box">
                <div class="upload-scrool">
                    <van-uploader class="upload-item" :after-read="onReadCoverPhoto">
                        <van-icon name="photograph"/>
                        <div class="cover-text">cover</div>
                        <van-icon v-if="form.coverPhoto" @click="onCoverPhotoCancel" name="close" class="photo-close"/>
                        <img v-if="form.coverPhoto" class="readed-photo" :src="form.coverPhoto" alt="">
                    </van-uploader>

                    <van-uploader class="upload-item" :after-read="(file)=>{onReadOtherPhoto(file, 0)}">
                        <van-icon name="photograph"/>
                        <van-icon v-if="form.otherPhoto[0]" @click="onOtherPhotoArrDel(0)" name="close"
                                  class="photo-close"/>
                        <img v-if="form.otherPhoto[0]" class="readed-photo" :src="form.otherPhoto[0]" alt="">
                    </van-uploader>

                    <van-uploader class="upload-item" :after-read="(file)=>{onReadOtherPhoto(file, 1)}">
                        <van-icon name="photograph"/>
                        <van-icon v-if="form.otherPhoto[1]" @click="onOtherPhotoArrDel(1)" name="close"
                                  class="photo-close"/>
                        <img v-if="form.otherPhoto[1]" class="readed-photo" :src="form.otherPhoto[1]" alt="">
                    </van-uploader>

                    <van-uploader class="upload-item" :after-read="(file)=>{onReadOtherPhoto(file, 2)}">
                        <van-icon name="photograph"/>
                        <van-icon v-if="form.otherPhoto[2]" @click="onOtherPhotoArrDel(2)" name="close"
                                  class="photo-close"/>
                        <img v-if="form.otherPhoto[2]" class="readed-photo" :src="form.otherPhoto[2]" alt="">
                    </van-uploader>

                    <van-uploader class="upload-item" :after-read="(file)=>{onReadOtherPhoto(file, 3)}">
                        <van-icon name="photograph"/>
                        <van-icon v-if="form.otherPhoto[3]" @click="onOtherPhotoArrDel(3)" name="close"
                                  class="photo-close"/>
                        <img v-if="form.otherPhoto[3]" class="readed-photo" :src="form.otherPhoto[3]" alt="">
                    </van-uploader>

                    <van-uploader class="upload-item" :after-read="(file)=>{onReadOtherPhoto(file, 4)}">
                        <van-icon name="photograph"/>
                        <van-icon v-if="form.otherPhoto[4]" @click="onOtherPhotoArrDel(4)" name="close"
                                  class="photo-close"/>
                        <img v-if="form.otherPhoto[4]" class="readed-photo" :src="form.otherPhoto[4]" alt="">
                    </van-uploader>

                </div>
            </div>
        </van-panel>


        <div class="submit-btn">
            <van-button size="large" class="btn" @click="onSubmit">Submit</van-button>
        </div>

    </div>
</template>

<script>

    import {feedback, feedbackUpload} from '../../static/api/zxy_api'

    import qs from 'qs';

    function setState(store) {
    }

    export default {
        name: 'feedback',
        metaInfo: {
            title: 'feedback',
            titleTemplate: '%s',
            meta: [
                {name: 'keywords', content: 'lavas PWA'},
                {name: 'description', content: '基于 Vue 的 PWA 解决方案，帮助开发者快速搭建 PWA 应用，解决接入 PWA 的各种问题'}
            ]
        },
        async asyncData({store, route}) {
            setState(store);
        },
        data() {
            return {
                form: {
                    radio: '1',
                    feedbackValue: '',
                    coverPhoto: '',
                    coverPhotoBlob: '',
                    otherPhoto: [],
                    otherPhotoBlob: [],
                },
            };
        },
        methods: {
            onClickLeft() {
                this.$router.go(-1)
            },
            onReadCoverPhoto(file) {
                // console.log(file, '读取文件')
                let e = file.file;
                let name = file.file.name;
                let that = this;
                this.setImageCompress(e, name, file.content, (imgObj) => {
                    // let imgObj = {
                    //     photoUrl: srcUrl,
                    //     photoBlob: blob,
                    //     name: name,
                    // }
                    that.form.coverPhoto = imgObj.photoUrl;
                    that.form.coverPhotoBlob = imgObj.photoBlob;
                    // console.log(imgObj, '回调拿到的压缩后的img')
                })

            },
            // 主图取消
            onCoverPhotoCancel() {
                this.form.coverPhoto = '';
                this.form.coverPhotoBlob = '';
            },
            // 读取附加图片
            onReadOtherPhoto(file, index) {
                // console.log(file, '读取文件')
                let e = file.file;
                let name = file.file.name;
                let that = this;
                this.setImageCompress(e, name, file.content, (imgObj) => {
                    // let imgObj = {
                    //     photoUrl: srcUrl,
                    //     photoBlob: blob,
                    //     name: name,
                    // }

                    // vue是通过检测get,set才得知数据是否更新的，而对于数组来说，是没有get，set方法的，所以需要我们自己手动触发，需要发送消息通知vue
                    that.$set(this.form.otherPhoto, index, imgObj.photoUrl)

                    // 数组blob (可能为空 上传需要判断剔除)
                    that.form.otherPhotoBlob[index] = imgObj.photoBlob;

                    // console.log(imgObj, '回调拿到的压缩后的img')
                })
            },
            //onOtherPhotoArrDel 额外图片删除
            onOtherPhotoArrDel(index) {
                this.$set(this.form.otherPhoto, index, '')
                this.form.otherPhotoBlob[index] = '';
            },
            // 压缩图片
            setImageCompress(e, name, content, callback) {
                let img = new Image()
                img.src = content;
                let canvas = document.createElement('canvas')
                let context = canvas.getContext('2d')
                let self = this
                img.onload = function () {
                    // 图片原始尺寸
                    let originWidth = this.width
                    var originHeight = this.height
                    // 最大尺寸限制
                    let maxWidth = 1000
                    let maxHeight = 1000
                    // 目标尺寸
                    let targetWidth = originWidth
                    let targetHeight = originHeight
                    // 图片尺寸超过400x400的限制
                    if (originWidth > maxWidth || originHeight > maxHeight) {
                        if (originWidth / originHeight > maxWidth / maxHeight) {
                            // 更宽，按照宽度限定尺寸
                            targetWidth = maxWidth
                            targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                        } else {
                            targetHeight = maxHeight
                            targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                        }
                    }
                    // canvas对图片进行缩放
                    canvas.width = targetWidth
                    canvas.height = targetHeight
                    // 清除画布
                    context.clearRect(0, 0, targetWidth, targetHeight)

                    // 图片压缩
                    context.drawImage(img, 0, 0, targetWidth, targetHeight)

                    // canvas转为blob并上传
                    canvas.toBlob((blob) => {
                        let srcUrl = URL.createObjectURL(blob)
                        let imgObj = {
                            photoUrl: srcUrl,
                            photoBlob: blob,
                            name: name,
                        }
                        callback(imgObj);
                    }, 'image/jpeg', 0.9)
                }
            },
            //  表单提交
            onSubmit() {
                // 表单校验

                let data = {
                    feedbackTypeId: this.form.radio || '1',
                    feedbackValue: this.form.feedbackValue || '',
                }

                let config = {
                    'Content-Type': 'multipart/form-data'
                }

                this.$toast({
                    mask: true,
                    message: 'loading...'
                });

                data = qs.stringify(data)

                feedback(data, config).then((res) => {

                    if (res.data.errorID == 0) {

                        if (!(this.form.coverPhotoBlob || (this.form.otherPhotoBlob.length > 0))) {
                            this.$toast.clear();
                            this.$toast.success('Successful')
                            this.$router.push('/')
                            return;
                        }

                        // 如果表单上传成功之后（获取到feedbackId）

                        // 图片数据上传准备  一个数组，第一张为主图
                        let formData = new FormData();

                        formData.append('file', this.form.coverPhotoBlob)

                        // 需要剔除空数据
                        for (let i = 0; i < this.form.otherPhotoBlob.length; i++) {
                            if (this.form.otherPhotoBlob[i]) {
                                formData.append('file', this.form.otherPhotoBlob[i])
                            }
                        }

                        let feedbackId = res.data.object.feedbackId || '';

                        // 如果成功之后 上传图片
                        feedbackUpload(formData, feedbackId).then((res) => {
                            if (res.data.errorID == 0) {
                                this.$toast.clear();
                                this.$toast.success('Successful')
                                this.$router.push('/')
                            } else {
                                this.$toast.clear();
                                this.$toast.fail('failed');
                            }
                        }).catch((e) => {
                            this.$toast.clear();
                        })

                    } else {
                        this.$toast.clear();
                        this.$toast.fail('failed');
                        return;
                    }

                }).catch((e) => {
                    this.$toast.clear();
                    // console.log(e)
                })
            },
        },
        mounted() {
            // sotre 作为全局的状态管理 慎重修改
            // 取值方式
            // console.log(this.$store.state.store.localLang, 'localLang')
            // this.$store.commit('store/updateLang', 'US')
            // console.log(this.$store.state.store.localLang, 'localLang')

            // 导入地区选择的json

        }
    };
</script>

<style>
    /*css reset 设置了input的line-height默认值为1.15 造成干扰*/
    .page-sell input {
        line-height: unset;
    }
</style>
<style scoped>

    .upload-box {
        padding: 0 15px;
        height: 92px;
        margin: 10px 0;
        overflow-x: scroll;
        overflow-y: hidden;
    }

    .upload-scrool {
        width: 560px;
    }

    .upload-item {
        width: 80px;
        height: 80px;
        border: 1px solid #ededed;
        text-align: center;
        margin-right: 6px;
    }

    .cover-text {
        position: absolute;
        bottom: 4px;
        left: 0;
        right: 0;
        margin: 0 auto;
        z-index: 300;
        color: #000;
    }

    .readed-photo {
        position: absolute;
        left: 0;
        bottom: 0;
        z-index: 200;
        width: 80px;
        height: 80px;
    }

    .photo-close {
        position: absolute;
        right: 10px;
        top: 4px;
        z-index: 300;
        width: 8px;
        height: 8px;
    }

    .submit-btn {
        width: 90%;
        padding: 30px 0 40px 0;
        margin: 0 auto;
    }

    .submit-btn .btn {
        border-radius: 5px;
        border: 1px solid #FF9A03;
        color: #FF9A03;
    }

    .type-box {
        padding: 20px 15px;
    }

</style>
<style>
    .page-sell .van-field .van-cell__title {
        max-width: 80px !important;
    }

    .page-sell .van-field__control {
        text-align: left;
        margin-right: -26px;
    }

    .page-sell .van-icon-photograph {
        font-size: 28px;
        line-height: 80px !important;
    }

    .page-sell .van-field__control:disabled {
        opacity: 1;
        color: initial !important;
        background-color: transparent;
    }
</style>
